package com.heima.comment.service.impl;

import com.heima.apis.user.IUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.CommentRepayVo;
import com.heima.comment.service.ApCommentRepayService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentRepayServiceImpl implements ApCommentRepayService {
    @Autowired
    private IUserClient userClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存回复的评论
     * @param dto
     * @return
     */
    public ResponseResult save(CommentRepaySaveDto dto){
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.保存评论
        ApUser apUser = userClient.findUserById(user.getId());
        ApCommentRepay apCommentRepay=new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //4.更新回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论回复列表
     * @param dto
     * @return
     */
    public ResponseResult load(CommentRepayDto dto){
        //1.检查参数
        if(dto == null || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size = 20;
        //2.加载数据
        Query query= Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(size);
        List<ApCommentRepay> list = mongoTemplate.find(query, ApCommentRepay.class);
        //3.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user==null){
            return ResponseResult.okResult(list);
        }
        //这20条数据的id
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        //查询commentRepayLikes表中哪个评论是该用户点过的赞
        Query query1=Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        if (apCommentRepayLikes.size()==0){
            //若未查询到的话直接返回list
            return ResponseResult.okResult(list);
        }
        //若查询到的话--封装返回的数据--加入operation
        List<CommentRepayVo> resultList=new ArrayList<>();
        for (ApCommentRepay apCommentRepay : list) {
            CommentRepayVo vo=new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,vo);
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if (apCommentRepayLike.getCommentRepayId().equals(apCommentRepay.getId())){
                    vo.setOperation((short) 0);
                }
            }
            resultList.add(vo);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复评论
     * @param dto
     * @return
     */
    public ResponseResult like(CommentRepayLikeDto dto){
       //1.检查参数
        if(dto == null || dto.getCommentRepayId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        //3.点赞
        if (apCommentRepay!=null&&dto.getOperation()==0){
            //更新点赞评论数
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
            //保存点赞数据
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
        }else{  //取消点赞
            //更新点赞评论数
            int i = apCommentRepay.getLikes()-1;
            i=i<0?0:i;
            apCommentRepay.setLikes(i);
            mongoTemplate.save(apCommentRepay);
            //删除点赞数据
            Query query=Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query,ApCommentRepayLike.class);
        }
        //封装返回数据likes的个数
        Map<String,Object> map=new HashMap<>();
        map.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
